import React,{PureComponent} from 'react'
import {View,Button,SafeAreaView,Text,StyleSheet,TextInput,ScrollView,Dimensions,TouchableOpacity,Image,FlatList} from 'react-native'
import color from "../../../widget/color";
import PayAlertDialog from '../../../widget/dialog/PayAlertDialog'

import api from '../../../api/api'
import method from '../../../api/method'
import {fetchGetRequest, fetchPostRequest} from '../../../api/NetworkTool'
import {NavigationActions} from "react-navigation";
import MineUnPayDetailCourseCell from '../../../widget/mine/MineUnPayDetailCourseCell'
import XPay from "react-native-puti-pay";
import Tips from "react-native-root-tips";
// import * as WeChat from "react-native-wechat";
// import Alipay from "react-native-yunpeng-alipay";
const {width, height} = Dimensions.get('window')
import NetTool from "../../../api/NetTool";
import BuySuccessScene from '../../detail/BuySuccessScene'


export default class MineUnPayDetailScene extends PureComponent{
    static navigationOptions = ({navigation}: any) => ({
        headerTintColor:'rgba(0,0,0,0.8)',
        title:'未付款',
        headerRight:<Text/>,
        headerLeft:<TouchableOpacity onPress={()=>{
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>
    });
    constructor(props){
        super(props)
        this.state = {
            payShow:false,
            info:{
                order:{},
                course:{},
                address:{},
            },

            show_alert:false,
            courses:[],
            address:{},
        }
        XPay.setAlipayScheme('alipayDemo')
        XPay.setWxId('wx8ad5c98436e7aefa')
    }





    componentDidMount() {
        const {orderId} = this.props.navigation.state.params

        let params = {
            orderId:orderId,
        }
        fetchGetRequest(api.getOrderDetail,method.get,params)
            .then(res=>{

                this.setState({info:res,courses:res.course,address:res.address})
            })
            .catch(err=>{})

    }

    pay(payment){

        const {course} = this.state.info
        const {address} = this.state.info


        // var courseArr = []
        //
        // var couponStr = ''
        //
        //
        // course.forEach(info=>{
        //     courseArr.push(info.id)
        //     if (info.coupon.price){
        //         let coupon_str = '(' + info.id + ',' + info.coupon.id + ')' + ','
        //         couponStr += coupon_str
        //     }else {
        //         let coupon_str = '(' + info.id + ','  + '0)' + ','
        //         couponStr += coupon_str
        //     }
        // })
           let  params = {
               order_sn:this.state.info.order.order_sn,
                payment:payment,
                clientType:'app',
             }




        fetchGetRequest(api.responsorPay,method.get,params)
            .then(res=>{
                console.log(res.payParam)
                this.sponsorPay(payment,res.payParam)
            })
            .catch(err=>{
                Tips.showInfo(err,{mask:true})
            })
    }
    sponsorPay(payment,params) {
        if(payment == 'alipay'){
            XPay.alipay(params,(res)=>{
                if (res.resultStatus == '9000') {
                    Tips.showSuccess('购买成功',{mask:true})
                    this.props.navigation.navigate('BuySuccessScene')
                }else if(res.resultStatus == '8000'){
                    Tips.showInfo('支付确认中...',{mask:true})
                }else {
                    Tips.showFail('购买失败',{mask:true})
                }
            })

        }else if(payment == 'wxpay'){
            let wechat_params = {
                partnerId:params.partnerid,
                prepayId: params.prepayid,
                packageValue:params.package,
                nonceStr: params.noncestr,
                timeStamp: params.timestamp,
                sign: params.sign,
            }
            XPay.wxPay(wechat_params,(res)=>{
                console.log('res wchat',res)
                if(res.errCode == 0){
                    Tips.showSuccess('购买成功',{mask:true})
                    this.props.navigation.navigate('BuySuccessScene')
                }else {
                    Tips.showFail('购买失败',{mask:true})
                }
            })
        }


    }

    render(){

        let address = this.state.address
        // let address = this.state.info.address
        let disprice = this.state.info.order.discount
        let yingPrice = (this.state.info.order.amount - this.state.info.order.discount) > 0?(this.state.info.order.amount - this.state.info.order.discount):0

        let dis = (disprice) > 0?-disprice:0
        return (
           <SafeAreaView style={{flex:1}}>
               <ScrollView>
                   <View style={{paddingLeft:12,paddingRight:12,paddingBottom:15,paddingTop:15,backgroundColor:'white'}}>
                       <Text style={{color:'#111111', fontSize:13, fontWeight:'bold',marginBottom:10}}>订单信息</Text>
                       <View style={{flexDirection:'row',alignItems:'center'}}>
                           <Text style={styles.text_show}>订单号:</Text>
                           <Text style={styles.text_data}>{this.state.info.order.order_sn}</Text>
                       </View>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
                           <Text style={styles.text_show}>下单时间：</Text>
                           <Text style={styles.text_data}>{this.state.info.order.pay_time}</Text>
                       </View>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
                           <Text style={styles.text_show}>订单状态：</Text>
                           <Text style={styles.text_data}>未付款</Text>
                       </View>
                   </View>
                   <View style={{width:width,height:2,backgroundColor:'#F9F9F9'}}/>

                   <View style={{paddingLeft:12,paddingRight:12,paddingBottom:15,backgroundColor:'white'}}>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:15}}>
                           <Text style={{color:'#111111', fontSize:13, fontWeight:'bold'}}>收货人信息</Text>
                       </View>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
                           <Text style={styles.text_show}>收货人：</Text>
                           <Text style={styles.text_data}>{address.receiver}</Text>
                       </View>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
                           <Text style={styles.text_show}>联系电话：</Text>
                           <Text style={styles.text_data}>{address.mobile}</Text>
                       </View>
                       <View style={{flexDirection:'row',alignItems:'flex-start',marginTop:10}}>
                           <Text style={[styles.text_show,{marginTop:2}]}>具体地址：</Text>
                           <Text style={[styles.text_data,{width:(width - 100)}]}>{address.city_name + address.address}</Text>
                       </View>
                   </View>
                   <View style={{width:width,height:2,backgroundColor:'#F9F9F9'}}/>
                   <View style={{paddingLeft:12,paddingRight:12,paddingBottom:5,backgroundColor:'white'}}>
                       <Text style={{color:'#111111', fontSize:13, fontWeight:'bold',marginTop:15}}>课程详情</Text>
                       <FlatList
                           style={{marginTop:5}}
                           data={this.state.courses}
                           renderItem={this.renderCell}
                           keyExtractor={this.keyExtractor}
                           ItemSeparatorComponent={()=><View style={{marginLeft:8,width:width-40,height:1,backgroundColor:'rgba(0,0,0,0.25)'}}/>}
                       />
                   </View>
                   <View style={{width:width,height:2,backgroundColor:'#F9F9F9'}}/>
                   <View style={{paddingLeft:12,paddingRight:12,paddingBottom:15,backgroundColor:'white'}}>
                       <Text style={{color:'#111111', fontSize:13, fontWeight:'bold',marginTop:15}}>结算信息</Text>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
                           <Text style={{color:'rgba(0,0,0,0.7)',fontSize:12}}>订单金额</Text>
                           <View style={{flex:1}}/>
                           <Text style={{color:'rgba(0,0,0,0.8)',fontSize:12,fontWeight:'700',marginRight:8}}>{this.state.info.order.amount}</Text>
                       </View>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
                           <Text style={{color:'rgba(0,0,0,0.7)',fontSize:12}}>优惠金额</Text>
                           <View style={{flex:1}}/>
                           <Text style={{color:'rgba(0,0,0,0.8)',fontSize:12,fontWeight:'700',marginRight:8}}>{dis}</Text>
                       </View>
                       <View style={{flexDirection:'row',alignItems:'center',marginTop:10}}>
                           <Text style={{color:'rgba(0,0,0,0.7)',fontSize:12}}>应付金额</Text>
                           <View style={{flex:1}}/>
                           <Text style={{color:'rgba(0,0,0,0.8)',fontSize:12,fontWeight:'700',marginRight:8}}>{yingPrice}</Text>
                       </View>
                   </View>
               </ScrollView>
               <PayAlertDialog onPress={(payment)=>{
                   this.pay(payment)
               }} info={this.state.info.order} show={this.state.payShow} closeModal={(show)=>{
                   this.setState({payShow:show})
               }}/>
               <View style={{flexDirection:'row',height:50,width:width,}}>

                   <TouchableOpacity onPress={()=>{
                       if(!address.id) {
                           Tips.showInfo('没有地址无法付款',{mask:true})
                           return
                       }
                       this.setState({payShow:true})}} style={{backgroundColor:'#DB3853',width:width,alignItems:'center',justifyContent:"center"}}>
                       <Text style={{color:'white',fontSize:16,fontWeight:'bold'}}>立即支付</Text>
                   </TouchableOpacity>
               </View>
           </SafeAreaView>
        )
    }
    renderCell = (item: any) => {
        return (
            <MineUnPayDetailCourseCell course={item.item}/>
        )
    }
    keyExtractor = (item: Object, index: number) => {
        return index + ''
    }
    // confirmOpress(){
    //     const {orderId} = this.props.navigation.state.params
    //
    //     let params = {
    //         orderId:orderId,
    //     }
    //     fetchPostRequest(api.cancelOrder,method.post,params)
    //         .then(res=>{
    //             this.props.navigation.goBack()
    //             this.props.navigation.state.params.callback('回调参数')
    //         })
    //         .catch(err=>{})
    // }
    // cancelOrder(){
    //     this.setState({show_alert:true})
    //
    //
    // }
}
const styles = StyleSheet.create({

    text_show:{
        color:'rgba(0,0,0,0.5)',
        fontSize:12,
        fontWeight:'200',
        width:64,
    },
    text_data:{
        fontSize:13,
        color:'black',
        marginLeft:8,
        marginRight:12,
    },
    title_show_jie_e:{
        color:'rgba(0,0,0,0.7)',
        fontWeight:'bold',
        fontSize:12,
    },
    title_data_jie_e:{
        color:'rgba(0,0,0,0.8)',
        fontSize:18,
        fontWeight:'700',
    },
    title_view:{
        flexDirection:'row',
        backgroundColor:'white',
        alignItems:'center',
    },
})